/**  
 * 文 件 名: ConnectionFactory.java  
 * 描    述：   
 * 版    权：Copyright (c)20012-2012 tongzhou All Rights Reserved.
 * 公    司: 同舟 
 * 作    者：彭定雄                     
 * 版    本: 1.0  
 * 创建时间: 2012-10-27
 *  
 * 修改历史：  
 * 时间                             作者                       版本                        描述  
 * ------------------------------------------------------------------  
 * 2012-10-27        彭定雄                1.0          1.0 Version  
 */       

package com.tongzhou.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.tongzhou.util.DES;

public class ConnectionFactory {
	private static Logger log = Logger.getLogger(ConnectionFactory.class.getName()) ;
	
	private final static String POOL_NAME = "oss" ;
	
	private static Class driverClass = null;    
    private static ObjectPool connectionPool = null;   
    
	private static String driver ;
	private static String url ;
	private static  String username ;
	private static  String password ;
	private static int initSize ;
	private static int maxIdle ;
	private static int minIdle ;
	private static int maxWait ;
	private static int maxActive ;
	
	static{
		try {
			parseConfigFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**   
     * 装配配置文件   
     * initProperties       
     */ 
	public static void parseConfigFile() throws Exception{
		SAXReader reader = new SAXReader();
		Document doc =  reader.read(ConnectionFactory.class.getResourceAsStream("/db.xml"));
		Element root = doc.getRootElement();
		driver = root.elementText("driverClass");
		url = root.elementText("url");
		username = root.elementText("username");
		password = root.elementText("password");
		password = DES.decrypt(password);
		initSize = 10 ;
		try{
			initSize = Integer.parseInt(root.elementText("initSize"));
		}catch(Exception e){}
		maxIdle = 20 ;
		try{
			maxIdle = Integer.parseInt(root.elementText("maxIdle"));
		}catch(Exception e){}
		minIdle = 5 ;
		try{
			minIdle = Integer.parseInt(root.elementText("minIdle"));
		}catch(Exception e){}
		maxActive = 100 ;
		try{
			maxActive = Integer.parseInt(root.elementText("maxActive"));
		}catch(Exception e){}
		maxWait = 1000 ;
		try{
			maxWait = Integer.parseInt(root.elementText("maxWait"));
		}catch(Exception e){}
		log.info("driverClass:"+driver);
		log.info("url:"+url);
		log.info("initSize:"+initSize);
		log.info("maxIdle:"+maxIdle);
		log.info("minIdle:"+minIdle);
		log.info("maxActive:"+maxActive);
		log.info("maxWait:"+maxWait);
	}
	
	/**    
     * 初始化数据源    
     */     
    private static synchronized void initDataSource() {             
        if (driverClass == null) {     
            try {     
                driverClass = Class.forName(driver);     
            } catch (ClassNotFoundException e) {     
                e.printStackTrace();    
            }     
        }     
    }     
     
    /**    
     * 连接池启动    
     * @throws Exception    
     */     
    public static void StartPool() {    
        initDataSource();     
        if (connectionPool != null) {     
            ShutdownPool();     
        }      
        try {     
            connectionPool = new GenericObjectPool(null);     
            org.apache.commons.dbcp.ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);     
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);     
            Class.forName("org.apache.commons.dbcp.PoolingDriver");     
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");     
            driver.registerPool(POOL_NAME, connectionPool);                  
        } catch (Exception e) {     
            e.printStackTrace();    
        }     
    }     
     
    /**    
     * 释放连接池    
     */     
    public static void ShutdownPool() {     
        try {     
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");     
            driver.closePool(POOL_NAME);    
        } catch (SQLException e) {     
            e.printStackTrace();    
        }     
    }         
     
    /**    
     * 取得连接池中的连接    
     * @return    
     */     
    public static Connection getConnection() {     
        Connection conn = null;     
        if(connectionPool == null)     
            StartPool();     
        try {     
            conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"+POOL_NAME);     
            if(conn.isClosed()){
            	conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"+POOL_NAME); 
            }
        } catch (SQLException e) {     
            e.printStackTrace();    
        }     
        return conn;     
    }     
    
    public static void main(String[] args) {            
       System.out.println(ConnectionFactory.getConnection());
    }
}
